﻿Public Class Form1

    Private mXmlFilePath As String

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        mXmlFilePath = Application.StartupPath & "\XmlDatabaseDemo.xml"
        If My.Computer.FileSystem.FileExists(mXmlFilePath) = True Then
            DsXmlDbDemo.ReadXml(mXmlFilePath)
            DsXmlDbDemo.AcceptChanges()
            Call Data_Update()
        End If

    End Sub

    Private Sub Data_Update()

        Dim mynum As Integer
        Dim myval As String
        Dim myname As String
        Dim myfname As String
        Dim mylname As String
        Dim dc As DataColumn
        Dim dr As DataRow
        Dim dtCustomers As DataTable

        dtCustomers = DsXmlDbDemo.Tables("Customers")

        For Each dc In dtCustomers.Columns
            myval = dc.ColumnName
            Select Case myval
                Case "Name"
                    mynum = mynum + 1
                Case "FName"
                    mynum = mynum + 1
                Case "LName"
                    mynum = mynum + 1
            End Select
        Next

        If mynum = 3 Then
            For Each dr In dtCustomers.Rows
                myname = dr("Name")
                If myname <> "" Then
                    myfname = ""
                    mylname = myname
                    mynum = InStrRev(myname, " ")
                    If mynum > 0 Then
                        myfname = Mid(myname, 1, mynum - 1)
                        mylname = Mid(myname, mynum + 1)
                    End If
                    dr.Item("FName") = myfname
                    dr.Item("LName") = mylname
                    dr.Item("Name") = ""
                    Stop
                End If
            Next
        End If

    End Sub

    Private Sub CustomersBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CustomersBindingNavigatorSaveItem.Click
        Me.Validate()
        CustomersBindingSource.EndEdit()
        OrdersBindingSource.EndEdit()
        If DsXmlDbDemo.HasChanges Then
            Stop
            DsXmlDbDemo.WriteXml(mXmlFilePath)
            DsXmlDbDemo.AcceptChanges()
        End If
    End Sub

    Private Sub OrdersDataGridView_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OrdersDataGridView.Enter
        CustomersBindingSource.EndEdit()
    End Sub

End Class
